﻿using System;
using System.Collections.Generic;

namespace CodeIn.Diagnostics {

	public abstract class BaseMessageHandler {
		public bool IsMuted { get; set; }
		private int tabCount = 0;
		private int tabSpaces = 4;
		private bool isNewLine = true;

		public BaseMessageHandler() {
			IsMuted = false;
		}

		public void Write(string text) {
			if (text == null)
				return;

			text = text.Replace("\n", "\n" + GetTabString());
			if (isNewLine) {
				isNewLine = false;
				WriteOverride(GetTabString() + text);
			} else {
				WriteOverride(text);
			}
		}

		public void Write(string format, params object[] args) {
			Write(string.Format(format, args));
		}

		public void WriteLine(string line) {
			if (line == null)
				return;

			line = line.Replace("\n", "\n" + GetTabString());
			if (isNewLine)
				WriteOverride(GetTabString() + line + Environment.NewLine);
			else
				WriteOverride(line + Environment.NewLine);
			isNewLine = true;
		}

		public void WriteLine(string format, params object[] args) {
			WriteLine(string.Format(format, args));
		}

		public void WriteWarningLine(string line) {
			WriteLine("[WARNING] " + line);
		}

		public void WriteWarningLine(string format, params object[] args) {
			WriteWarningLine(string.Format(format, args));
		}

		public void WriteErrorLine(string line) {
			WriteLine("[ERROR] " + line);
		}

		public void WriteErrorLine(string format, params object[] args) {
			WriteErrorLine(string.Format(format, args));
		}

		public void WriteSeparator() {
			int length = 70 - GetTabString().Length;
			WriteLine(new string('-', length));
		}

		public void Indent() {
			tabCount++;
		}

		public void Unindent() {
			tabCount = tabCount > 0 ? tabCount - 1 : 0;
		}

		public void OpenSection(string name) {
			WriteSeparator();
			WriteLine("-- " + name);
			WriteSeparator();
			Indent();
		}

		public void CloseSection() {
			Unindent();
		}

		protected abstract void WriteOverride(string message);

		private string GetTabString() {
			string ret = "";
			for (int i = 0; i < tabCount; i++)
				ret += new string(' ', tabSpaces);
			return ret;
		}
	}
}
